package com.zzyl.nursing.service.impl;

import java.io.Reader;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.DeviceData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

/**
 * 报警规则Service业务层处理
 *
 * @author Lee
 * @date 2025-10-22
 */
@Slf4j
@Service
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper,AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return save(alertRule)?1:0;
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return updateById(alertRule)?1:0;
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void alertFilter() {
        List<AlertRule> list = this.list();
        if (CollUtil.isEmpty(list)){
            return;
        }
        List<Object> values = redisTemplate.boundHashOps(CacheConstants.IOT_DEVICE_LAST_DATA).values();
        if (CollUtil.isEmpty(values)){
            return;
        }
       List<DeviceData> deviceDataList = new ArrayList<>(); //大集合
        for (Object value : values) {  //value是小集合
            List<DeviceData> list1 = JSONUtil.toList(value.toString(), DeviceData.class);
            deviceDataList.addAll(list1);
        }

        //数据报警处理器,一条一条处理
        for (DeviceData deviceData : deviceDataList) {
            alertJob(deviceData);
        }
    }


    private ScriptEngine scriptEngine;
    private void alertJob(DeviceData deviceData) {
        //查询所有的设备
        //根据产品id, 指定设备  谁的设备id,
        LambdaQueryWrapper<AlertRule> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(AlertRule::getProductKey,deviceData.getProductKey());
        queryWrapper1.eq(AlertRule::getFunctionId,deviceData.getFunctionId());
        queryWrapper1.eq(AlertRule::getIotId,-1);
        List<AlertRule> list1 = this.list(queryWrapper1);

        LambdaQueryWrapper<AlertRule> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(AlertRule::getProductKey,deviceData.getProductKey());
        queryWrapper2.eq(AlertRule::getFunctionId,deviceData.getFunctionId());
        queryWrapper2.eq(AlertRule::getIotId,deviceData.getIotId());

        List<AlertRule> list2 = this.list(queryWrapper1);

        //合并集合
        Collection<AlertRule> alertRules = CollUtil.addAll(list1, list2);
        if (alertRules.isEmpty()){
            return;
        }

        for (AlertRule alertRule : alertRules) {
            deviceDataAlarmHandler(alertRule,deviceData);
        }


    }




    private void deviceDataAlarmHandler(AlertRule alertRule, DeviceData deviceData) {

        String alertCountKey=  CacheConstants.ALERT_TRIGGER_COUNT_PREFIX+deviceData.getIotId()+ deviceData.getProductKey()+alertRule.getFunctionId()+alertRule.getId();
        String slientKey = CacheConstants.ALERT_SILENT_PREFIX+deviceData.getIotId()+ deviceData.getProductKey()+ alertRule.getFunctionId()+alertRule.getId();

        //第一层校验:判断生效时间
        log.info("第一层校验:判断生效时间");
        String period = alertRule.getAlertEffectivePeriod();
        String[] split = period.split("~");
        LocalDate start = LocalDate.parse(split[0]);
        LocalDate end = LocalDate.parse(split[1]);
        LocalDate alarmTime = deviceData.getAlarmTime().toLocalDate();
        if (alarmTime.isBefore(start) || alarmTime.isAfter(end)) {
            return;
        }

        log.info("第二 层校验:判断数据是否达到阈值");
        //表达式               上报的数据 + 符号 + 阈值
        String expression = (deviceData.getDataValue() + alertRule.getOperator() + alertRule.getValue());
        Boolean isReach = false;
        try {
            isReach  = (Boolean) scriptEngine.eval(expression);

        } catch (ScriptException e) {
            e.printStackTrace();
        }

        if(!isReach){

            redisTemplate.delete(alertCountKey);
        }
        log.info("第三层校验:判断沉默周期");
        Boolean hasKey = redisTemplate.hasKey(alertCountKey);
        if (hasKey){
            return;
        }

        log.info("第四层校验:判断持续周期");
        Long alertCount = redisTemplate.boundValueOps(slientKey).increment();
        if(alertCount>=alertRule.getDuration()){
            log.info("可以报警了");
            redisTemplate.delete(alertCountKey);
            redisTemplate.boundValueOps(slientKey).set(slientKey,alertRule.getDuration(), TimeUnit.MINUTES);
            System.out.println("校验全部通过");

            // 插入报警数据
            insertAlertData(alertRule, deviceData);
        }


    }

    private void insertAlertData(AlertRule alertRule, DeviceData deviceData) {
    }

}